<?php
declare (strict_types=1);

namespace app\sysuser\controller\system;

use app\common\controller\SysBackend;
use app\common\enums\UserConstantsEnum;
use app\common\enums\UserStatusEnum;
use app\common\facade\Token;
use app\common\model\banxi\Grade as GradeModel;
use app\common\model\banxi\sys\SysUser as SysUserModel;
use ba\Exception;
use think\db\exception\DbException;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Validate;
use think\validate\ValidateRule;

class SysUser extends SysBackend
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = [];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new SysUserModel();
    }


    /**
     * 分页查询
     * @return void
     * @throws DbException
     */
    public function listPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $list = $this->model->with(['roleInfo'])->where($where)
            ->order(['id' => 'desc'])
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit']
            ]);
        $this->ok('操作成功', result_row($list));
    }

    /**
     * 查询
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get()
    {
        $param = $this->request->param(["query" => []]);
        if (empty($param['query'])) {
            $this->fail('请传递你要查询的记录');
        }
        $where = get_query($param);
        $info = $this->model->with(['roleInfo'])->where($where)
            ->find();
        if (empty($info)) {
            $this->fail('记录不存在');
        }
        $this->ok('操作成功', removeNull($info));
    }

    public function saveOrUpdate()
    {
        $param = $this->request->param();
        try {
            $userId = $param['id'] ?? null;
            $sysUser = $param;
            if ($userId) {
                unset($sysUser['username']);
                unset($sysUser['password']);
                $this->model->updateUser($sysUser);
            } else {
                $sysUser['status'] = UserStatusEnum::NORMAL;
                $this->model->saveUser($sysUser);
            }
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }

    public function enable($userId)
    {
        try {
            $user = $this->model->where(['id' => $userId])->find();
            if (empty($user)) {
                throw new ValidateException('账号不存在');
            }
            if ($user['status'] == UserStatusEnum::NORMAL) {
                $updateStatus = UserStatusEnum::DISABLE;
                Token::clear($this->auth::TOKEN_TYPE, $userId);
            } else {
                $updateStatus = UserStatusEnum::NORMAL;
            }
            $user->save(['status' => $updateStatus]);
        } catch (Exception|PDOException|ValidateException $e) {
            $this->fail($e->getMessage());
        }
        $this->ok(UserStatusEnum::NORMAL == $updateStatus ? '启用成功' : '停用成功', [], self::NOTIFICATION);
    }

    public function resetPwd()
    {
        $param = $this->request->param(["id", 'password']);
        try {
            $userId = $param['id'];
            $sysUser = $this->model->where(['id' => $userId])->find();
            if (empty($sysUser)) {
                throw new ValidateException('账号不存在');
            }
            if (UserConstantsEnum::SUPER_ADMIN_ID == $userId) {
                throw new ValidateException('重置密码失败，超级管理员不可被操作');
            }
            $salt = createPasswordSalt();
            $password = createPassword($salt, $param['password']);
            $user = [
                'password' => $password,
                'salt' => $salt
            ];
            $sysUser->save($user);
            Token::clear($this->auth::TOKEN_TYPE, $userId);
        } catch (Exception|PDOException|ValidateException $e) {
            $this->fail($e->getMessage());
        }
        $this->ok('重置密码成功', [], self::NOTIFICATION);
    }


    public function del()
    {
        $param = $this->request->param(['id' => []]);
        try {
            $validate = Validate::rule([
                'id' => ValidateRule::isRequire(null, '请选择你要删除的记录'),
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            $this->model->deleteUserById($param['id']);
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }

    public function removes()
    {
        $param = $this->request->param(['ids' => []]);
        try {
            $validate = Validate::rule([
                'ids' => ValidateRule::isRequire(null, '请选择你要删除的记录'),
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            $this->model->deleteUserByIds($param['ids']);
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }
}
